<?php
namespace app\admin\controller;

use app\admin\model\Menulist;
use think\Cookie;
use think\Request;

class Menu extends Base
{
    protected function _initialize(){
        $this->checkLogin();
        $this->menuLoad();
    }
    /**
     * @param Request $request pid 父级id
     * @return mixed
     * 菜单列表
     */
    public function index(Request $request)
    {
        $data = $request->get();
        $menu = new Menulist();
        if(isset($data['pid']) and is_numeric($data['pid']) and $data['pid']>0){
            $pid['pid'] = $request->get()['pid'];
            $topWhere['id'] = $pid['pid'];
            $topMenuName = $menu->getOneMenu($topWhere);
            $this->assign('topMenuName',$topMenuName['name']);
        }else{
            $pid['pid'] = 0;
        }

        $rs = $menu->getAllMenu($pid);

        $this->assign('pid',$pid);
        $this->assign('rs',$rs);
        return $this->fetch();
    }

    /**
     * @param Request $request
     * @return mixed|void
     * 添加菜单，带链接则生成二级菜单
     */
    public function add(Request $request){
        if($request->post()){
            $admin_id = Cookie::get('admin_id');
            if($admin_id != 1){
                return $this->ajaxResult(3);
            }
            $data = $request->post();
            //控制器地址写入数据库
            $menu = new Menulist();
            //一级判断
            if($data['type'] == 0){
                //判断是否有空格
                if(strpos(' ',$data['clas']) == true) return $this->ajaxResult(0);
                //修改传参class键名,修改首字母大写
                $data['class'] = ucfirst($data['clas']);
                unset($data['clas']);
                //不能是空
                if($data['class'] =='')return $this->ajaxResult(0);
                //名字不能相同
                $whereName['name'] = $data['name'];
                $findName = $menu->getOneMenu($whereName);
                if($findName) return $this->ajaxResult(0);

            }

            //二级判断
            if($data['type'] == 1){

                //二级
                //判断是否有空格
                if(strpos(' ',$data['clas']) == true) return $this->ajaxResult(0);
                //修改传参class键名
                $data['class'] = lcfirst($data['clas']);
                unset($data['clas']);
                //名字不能相同
                $whereName['pid'] = 0;
                $whereName['name'] = $data['name'];
                $findName = $menu->getOneMenu($whereName);

                if($findName)return false;

                //链接不能相同
                $whereUrl['class'] = $data['class'];

                $findUrl = $menu->getOneMenu($whereUrl);
                if($findUrl)return $this->ajaxResult(0);

                //父级id不能为0
                if($data['pid'] == 0)return $this->ajaxResult(0);
            }
            //删除类型，插入数据库
            unset($data['type']);
            $rs = $menu->addMenu($data);
            /*
             * 一级创建类文件，
             * 二级写入方法 和 route
             *
             * */
            if($rs){
                $re = $this->createMenuController($request->post('type'),$data['class']);
                if($re == 0){
                    return $this->ajaxResult(0);
                }
                return $this->ajaxResult(1);
            }else{
                return $this->ajaxResult(0);
            }

        }
        $menu = new Menulist();
        $topWhere['pid'] = 0;
        $rs = $menu->getAllMenu($topWhere);
        $this->assign('rs',$rs);
        return $this->fetch();
    }

    public function del(Request $request){
        $data = $request->get();
        //删数据库
        $menuList = new Menulist();
        $menuWhere['url'] = $data['url'];
        $delData = $menuList->delMenu($menuWhere);
        if(!$delData)return $this->ajaxResult(0);
        //删除route
        $controllerName = explode('/',$data['url']);
        $isFile = $this->checkMenuController($controllerName[2]);
        $delRoute = $this->delRoute($isFile);
        if(!$delRoute)return $this->ajaxResult(0);
        //删文件


    }

    /**
     * @param $type 类型
     * @param $url  地址
     * @return bool
     * 创建控制器文件
     */
    public function createMenuController($type = '',$clas = ''){
        //不能为空
        if($type == '')return 0;
        if($clas == '')return 0;
        //type = 0 创建类文件
        if($type == 0){
            //创建文件
            //检查是否存在文件
            $isFile = $this->checkMenuController($clas);
            if($isFile == false){
                file_put_contents("../application/admin/controller/".$clas.".php","<?php\r\nnamespace app\admin\controller;\r\nclass ".$clas." extends Base\r\n{\r\n    protected function _initialize(){\r\n        \$this->menuLoad();\r\n    }\r\n    public function index(){\r\n        return \$this->fetch('public/help');\r\n    }\r\n}");//这里说一下\r\n在双引号下
                return 1;
            }
        }

        //type = 1  在类文件写方法，写入route
        if($type == 1){
            $menuList = new Menulist();
            //获取类id
            $getTopWhere['class'] = $clas;
            $topOne = $menuList->getOneMenu($getTopWhere);
            //获取类名
            $getTopClassWhere['id'] = $topOne['pid'];
            $topTwo = $menuList->getOneMenu($getTopClassWhere);
            //写入route
            $this->addRoute($topTwo['class'],$clas);
            //写入class文件
            $this->addFunction($topTwo['class'],$clas);
            return 1;
        }
        return 0;
    }

    public function delMenuController($fileName = ''){
        if($fileName =='' && $this->checkMenuController($fileName) == false)return false;

        $dir = '../application/admin/controller';
        $dh = opendir($dir);
    }

    /**
     * @param string $topClass  类名
     * @param string $secondClass  方法名
     * @return bool
     * 添加路由
     */
    public function addRoute($topClass = '',$secondClass =''){
        //删除最后一行
        $savestr='';
        $fp = file("../conf/route.php");

        $total = count($fp); //取得文件总行数
        $delnum = $total-1; //要删除的行序号
        foreach ($fp as $line)
        {
            //按行分解内容并
            $tmp[] = $line; //逐行写入数组
        }

        for($i=0;$i<$total;$i++){ //若$i的值不等于要删除的行序号
            if($i<>$delnum){
                $savestr .= $tmp[$i];
            }
        }
        //写入文件
        $fp = fopen('../conf/route.php','w');
        fwrite($fp,$savestr);
        fclose($fp);

        //添加路由和最后一行
        $fp = fopen('../conf/route.php','ab+');
        fwrite($fp,"    'admin/".$secondClass."'          =>  'admin/".$topClass."/".$secondClass."',\r\n];");
        fclose($fp);
        return true;
    }

    public function addFunction($clas = '',$func =''){
        //删除最后一行
        $savestr='';
        $fp = file("../application/admin/controller/".$clas.".php");

        $total = count($fp); //取得文件总行数
        $delnum = $total-1; //要删除的行序号
        foreach ($fp as $line)
        {
            //按行分解内容并
            $tmp[] = $line; //逐行写入数组
        }

        for($i=0;$i<$total;$i++){ //若$i的值不等于要删除的行序号
            if($i<>$delnum){
                $savestr .= $tmp[$i];
            }
        }

        //写入文件
        $fp = fopen('../application/admin/controller/'.$clas.'.php','w');
        fwrite($fp,$savestr);
        fclose($fp);

        //添加路由和最后一行
        $fp = fopen('../application/admin/controller/'.$clas.'.php','ab+');
        fwrite($fp,"\r\n    public function ".$func."(){\r\n        return \$this->fetch('public/help');\r\n    }\r\n}");
        fclose($fp);
        return true;
    }

    /**
     * @param string $keys
     * @return bool
     * 删除路由
     */
    public function delRoute($keys=''){
        //删除最后一行
        $savestr='';
        $fp = file("../conf/route.php");
        //$fp = file("D:/phpStudy/WWW/thinkphp/conf/route.php");
        $total = count($fp); //取得文件总行数
        foreach ($fp as $line)
        {
            //不过滤不包含的行
            if (!preg_match("/".$keys."/", $line))
            {
                //按行分解内容并
                $tmp[] = $line; //逐行写入数组
            }
        }

        for($i=0;$i<$total;$i++){
            $savestr .= $tmp[$i];
        }
        $fp = fopen('../conf/route.php','ab+');
        //$fp = fopen('D:/phpStudy/WWW/thinkphp/conf/route.php','w');
        fwrite($fp,$savestr);
        fclose($fp);
        return true;
    }


}
